package org.coc.betterchicago;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.coc.betterchicago.util.CookieManager;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

/**
 * @author manu
 *         http://www.pakzilla.com/2009/10/03/tutorial-java-based-twitter-app
 *         -on-google-app-engine/
 */
public class BetterChicagoAuth extends HttpServlet {
	private static final long serialVersionUID = 3028641923239977166L;

	public static Configuration CONFIGURATION;
	static {
		ConfigurationBuilder twitterAuthConfigBuilder = new ConfigurationBuilder();
		twitterAuthConfigBuilder.setOAuthConsumerKey("MzPoJ5BUGTospeQQ5qSg");
		twitterAuthConfigBuilder.setOAuthConsumerSecret("Gms8PseGe35yN3HnmQugkgDWyUVJMIomwWlmoCaJCo");
		CONFIGURATION = twitterAuthConfigBuilder.build();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	/**
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Long id = new CookieManager().parseIdCookie(request.getCookies());
		if (id != null) {
			TwitterOAuth oauth = new TwitterOAuth();
			User twitterUser = oauth.authorize(id);
			if (twitterUser != null) {
				System.out.println("found user:" + twitterUser.getScreenName());
				response.sendRedirect("xindex.html");
				return;
			}
		}

		HttpSession session = request.getSession();
		String attributeName = "requestToken";
		if (session.getAttribute(attributeName) == null) {
			try {
				Twitter twitter = new TwitterFactory(BetterChicagoAuth.CONFIGURATION).getInstance();
				RequestToken requestToken = twitter.getOAuthRequestToken();
				session.setAttribute(attributeName, requestToken);
				System.out.println("authorization url:" + requestToken.getAuthorizationURL());
				response.addCookie(new Cookie(attributeName, requestToken.getToken()));
			} catch (TwitterException e) {
				e.printStackTrace();
				response.sendRedirect("error.html");
			}
		}
		response.sendRedirect("login.html");

	}
}
